﻿using System;
using Microsoft.Practices.ObjectBuilder;

namespace Microsoft.Practices.CompositeUI.BuilderStrategies
{
    /// <summary>
    /// 	A <see cref = "BuilderStrategy" /> which is used to help the application startup sequence properly 
    /// 	initialize the root <see cref = "WorkItem" /> when it is created.
    /// </summary>
    internal class RootWorkItemInitializationStrategy : BuilderStrategy
    {
        #region Fields & Properties

        private readonly Action _callback;

        #endregion

        #region Constructors

        /// <summary>
        /// 	Creates a new instance of the RootWorkItemInitializationStrategy class using the given
        /// 	callback method.
        /// </summary>
        /// <param name = "callback">The  callback method to call when the <see cref = "WorkItem" /> is finishing its initialization.</param>
        public RootWorkItemInitializationStrategy(Action callback)
        {
            _callback = callback;
        }

        #endregion

        #region Build Up

        /// <summary>
        /// 	See <see cref = "BuilderStrategy.BuildUp" /> for more information.
        /// </summary>
        public override object BuildUp(IBuilderContext context, Type typeToBuild, object existing, string idToBuild)
        {
            var workItem = existing as WorkItem;
            if (workItem != null && workItem.Parent == null)
            {
                _callback();
            }
            return base.BuildUp(context, typeToBuild, existing, idToBuild);
        }

        #endregion
    }
}